﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;

namespace KantoorDienst
{
    public partial class Verkoop : Form
    {
        DBConnect db;
        DataTable pList;
        decimal subTotal = 0;
        public Verkoop()
        {
            InitializeComponent();
            
        }

        private void Verkoop_Load(object sender, EventArgs e)
        {
            db = new DBConnect();
            setupDataGridView();
            askForKNSA();
        }
        private void setupDataGridView()
        {
            pList = new DataTable();
            //all columns that we wanna see
            pList.Columns.Add("prod_id");
            pList.Columns.Add("barcode");
            pList.Columns.Add("name");
            pList.Columns.Add("price");
            pList.Columns.Add("cal_id");
            pList.Columns.Add("type");
            pList.Columns.Add("item_no");
            pList.Columns.Add("count");
            pList.Columns.Add("permit");

            dataGridView1.DataSource = pList;
            dataGridView1.AllowDrop = false;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.AllowUserToResizeColumns = false;
            dataGridView1.AllowUserToOrderColumns = false;
            dataGridView1.AllowUserToResizeRows = false;
            dataGridView1.BackgroundColor = Color.White;
            dataGridView1.Columns[0].HeaderText = "Product#";
            dataGridView1.Columns["count"].HeaderText = "aantal";
            this.dataGridView1.Columns["permit"].Visible = false;
            this.dataGridView1.Columns["cal_id"].Visible = false;

        }

        private void findProductBtn_Click(object sender, EventArgs e)
        {
            findProduct();
        }
        private void findProduct()
        {
            string s = searchBox.Text;
            try
            {
                DataTable dt = db.searchBarcode(s);
                DataRow dr = dt.Rows[0];//we only want the first result
                
                string curProd_id = dr["prod_id"].ToString();
                //check if product is already in the list
                bool alreadyExists = false;
                foreach (DataRow tablerow in pList.Rows)
                {
                    if (tablerow["prod_id"].ToString() == curProd_id)
                    {
                        alreadyExists = true; //we can now skip adding the row to the table

                        //add one count to already existing row
                        int curAmount = int.Parse( pList.Rows[pList.Rows.IndexOf(tablerow)]["count"].ToString()) ;
                        curAmount++;
                        pList.Rows[pList.Rows.IndexOf(tablerow)]["count"] = curAmount;
                        break;
                    }
                    
                }
                if(!alreadyExists){ //if item already exists, count++
                pList.ImportRow(dr);
                pList.Rows[pList.Rows.Count -1]["count"] = 1;
                }                
            }
            catch (IndexOutOfRangeException ex)
            {
                //no articles found with that barcode
                MessageBox.Show("no item found with this barcode");
            }
            searchBox.Text = "";
            calculatePrice();
        }
        private void calculatePrice()
        {
            subTotal = 0;
            foreach (DataRow dr in pList.Rows)
            {
                try
                { //try to add price to subtotal, if price is given
                    subTotal += (decimal.Parse(dr["price"].ToString())*decimal.Parse(dr["count"].ToString()));
                }
                catch (Exception)
                {

                }
            }
            priceLbl.Text = subTotal.ToString();
        }

        private void askForKNSA()
        {
            string knsa = Microsoft.VisualBasic.Interaction.InputBox("Scan de KNSA-pas om verder te gaan", "KNSA invoer", "", 100, 100);
            try
            {
                DataRow row = db.getMemberByKnsa(knsa).Rows[0];
                string initial = row["initial"].ToString();
                string tussenvoegsel = row["tussenvoegsel"].ToString();
                string lastName = row["lastName"].ToString();

                if (db.getAanwezigVandaag(knsa) == true) //controleren of persoon niet toevallig al aanwezig is
                {
                    //persoon al aangemeld, gewoon doorgaan
                    knsaLbl.Text = knsa;
                    nameLbl.Text = initial + " " + tussenvoegsel + " " + lastName;
                }
                else
                {
                    //persoon is nog niet aangemeld, eerst aanmelden!
                    //TODO: iets van afhandeling van error, message dat gebruiker aan moet melden en opnieuw askforknsa?
                    MessageBox.Show("Je bent vandaag nog niet aangemeld! In deze testversie boeit dat niets, maar normaal kan je niet verder\n bij deze heb ik je aangemeld :) ");
                    db.setAanwezig(knsa);
                    askForKNSA();
                }
            }
            catch (IndexOutOfRangeException i)
            {
                MessageBox.Show("gebruiker niet gevonden");
                askForKNSA();
                
            }
            

        }

        private Boolean permitNeeded()
        {
            Boolean permit = false;

            foreach (DataRow dr in pList.Rows)
            {
                try
                { //try to add price to subtotal, if price is given
                    MessageBox.Show(dr["permit"].ToString());
                    if (Boolean.Parse(dr["permit"].ToString()) == true)
                    {permit = true;}
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }

            return permit;
        }

        private string askForPermit()
        {
            return Microsoft.VisualBasic.Interaction.InputBox("Voor een verlofnummer in", "verlofnummer", "", 100, 100);

        }

        private void searchBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                findProduct();
            }
        }

        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            calculatePrice();
        }

        private void payBtn_Click(object sender, EventArgs e)
        {
            if (permitNeeded())
            {
                string permit = askForPermit();
            }

            addToDb();
            pList.Clear();
            priceLbl.Text = "0";
            askForKNSA();
        }
        private void addToDb()
        {
            db.addLog(pList);   
        }

    }
}
